using Auth.Application.DTO.Input;
using Auth.Application.DTO.Output;
using Auth.Application.Services;
using Auth.Result;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Auth.Api.Controllers
{
    /// <summary>
    /// 认证控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        private readonly IAuthService _authService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="authService">认证服务</param>
        public AuthController(IAuthService authService)
        {
            _authService = authService;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginInput">登录信息</param>
        /// <returns>登录结果</returns>
        [HttpPost("login")]
        public ActionResult<ApiResult<LoginOutput>> Login([FromBody] LoginInput loginInput)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new ApiResult<LoginOutput>
                {
                    Success = ResultCode.Fail,
                    Message = "请求参数不合法",
                    Data = null
                });
            }

            var result = _authService.Login(loginInput);
            return Ok(result);
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="registerInput">注册信息</param>
        /// <returns>注册结果</returns>
        [HttpPost("register")]
        public ActionResult<ApiResult<int>> Register([FromBody] RegisterInput registerInput)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new ApiResult<int>
                {
                    Success = ResultCode.Fail,
                    Message = "请求参数不合法",
                    Data = 0
                });
            }

            var result = _authService.Register(registerInput);
            return Ok(result);
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns>用户信息</returns>
        [HttpGet("userinfo")]
        
        public ActionResult<ApiResult<UserOutput>> GetUserInfo()
        {
            var userId = User.FindFirst("sub")?.Value;
            if (string.IsNullOrEmpty(userId) || !long.TryParse(userId, out long id))
            {
                return BadRequest(new ApiResult<UserOutput>
                {
                    Success = ResultCode.Fail,
                    Message = "无法获取用户ID",
                    Data = null
                });
            }

            var result = _authService.GetUserInfo(id);
            return Ok(result);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPassword">旧密码</param>
        /// <param name="newPassword">新密码</param>
        /// <returns>操作结果</returns>
        [HttpPost("change-password")]
        [Authorize]
        public ActionResult<ApiResult> ChangePassword([FromBody] ChangePasswordInput input)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new ApiResult
                {
                    Success = ResultCode.Fail,
                    Message = "请求参数不合法"
                });
            }

            var userId = User.FindFirst("sub")?.Value;
            if (string.IsNullOrEmpty(userId) || !long.TryParse(userId, out long id))
            {
                return BadRequest(new ApiResult
                {
                    Success = ResultCode.Fail,
                    Message = "无法获取用户ID"
                });
            }

            var result = _authService.ChangePassword(id, input.OldPassword, input.NewPassword);
            return Ok(result);
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="input">分页参数</param>
        /// <returns>用户列表</returns>
        [HttpGet("users")]
      
        public ActionResult<ApiPaging<UserOutput>> GetUsers([FromQuery] PageInput input)
        {
            var result = _authService.GetAllUsers(input);
            return Ok(result);
        }

        /// <summary>
        /// 健康检查
        /// </summary>
        /// <returns>健康状态</returns>
        [HttpGet("health")]
        public IActionResult Health()
        {
            return Ok("Healthy");
        }
        [HttpGet]
        public ApiResult<List<ShowUserDTO>> VueShowUserData()
        {
            return _authService.ShowUserData();
        }
    }

    /// <summary>
    /// 修改密码输入DTO
    /// </summary>
    public class ChangePasswordInput
    {
        /// <summary>
        /// 旧密码
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "旧密码不能为空")]
        public string OldPassword { get; set; }

        /// <summary>
        /// 新密码
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "新密码不能为空")]
        [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength = 6, ErrorMessage = "密码长度必须在6-100个字符之间")]
        public string NewPassword { get; set; }

        /// <summary>
        /// 确认新密码
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "确认密码不能为空")]
        [System.ComponentModel.DataAnnotations.Compare("NewPassword", ErrorMessage = "两次输入的密码不一致")]
        public string ConfirmNewPassword { get; set; }
    }
} 